package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.admin.AdminConstans;
import com.heima.common.user.UserConstans;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>  implements ApUserRealnameService {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ApUserMapper apUserMapper;


    //查询数据库ap_user_realname表，根据状态查询
    @Override
    public PageResponseResult loadListByStatus(AuthDto dto) {
         //检查数据
        if (dto==null) return (PageResponseResult)PageResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        dto.checkParam();
        //查询数据库ap_user_realname表，根据状态查询
        //构造查询条件
        QueryWrapper<ApUserRealname> wrapper=new QueryWrapper<>();
       if (dto.getStatus()==null){
           dto.setStatus((short)1);
       }
        wrapper.lambda().eq(ApUserRealname::getStatus,dto.getStatus());
        //分页条件查询所有
        Page<ApUserRealname> page=new Page<>(dto.getPage(),dto.getSize());
        IPage<ApUserRealname> page1 = page(page, wrapper);

        //Integer currentPage, Integer size, Integer total
       PageResponseResult pageResponseResult=new PageResponseResult( (int)page1.getCurrent(),(int)page1.getSize(),(int)page1.getTotal());
      pageResponseResult.setData(page1.getRecords());
      pageResponseResult.setCode(0);
      pageResponseResult.setErrorMessage("操作成功");
        /*ResponseResult result = PageResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        result.setData(page1.getRecords());*/
       /* return (PageResponseResult)result;*/
        return pageResponseResult;
    }

    /**
     * 根据状态进行审核
     * @param dto
     * @param status
     * @return
     */
    @Override
    @Transactional
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //检查数据
        if (dto==null||dto.getId()==null||statusCheck(status)){
          return   ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //修改状态
        ApUserRealname apUserRealname=new ApUserRealname();
       // apUserRealname.setStatus(status);
        apUserRealname.setId(dto.getId());
        if (dto.getStatus()!=null){
            apUserRealname.setStatus(dto.getStatus());
        }
        updateById(apUserRealname);

       // int i=1/0;
        //3 认证通过添加自媒体账号和作者账号
        if (status.equals(AdminConstans.PASS_AUTH)){
            ResponseResult createResult = createWmUserAndAuthor(dto);
            if (createResult != null) {
                return createResult;
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 创建自媒体账号， 以及作者账号
     * @param dto
     * @return
     */
    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        //添加自媒体账号, 查询ap_user信息封装到wmuser中
        ApUserRealname aur = getById(dto.getId());
        if (aur==null||aur.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = apUserMapper.selectById(aur.getUserId());
        if (apUser==null||apUser.getName()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 检测自媒体用户是否存在
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser==null||wmUser.getId()==null){
            wmUser=new WmUser();
           // wmUser.setApAuthorId(apUser.getId());
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
           wemediaFeign.saveOrUpdate(wmUser);
        }

        //创建作者账号
        createAuthor(wmUser);
        //修改ap_user标记
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
        return null;
    }


    /**
     * 创建自媒体账号
     * @param wmUser
     * @return
     */
    private void createAuthor(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        System.out.println("WmUser:"+wmUser);
        System.out.println("apUserId:"+apUserId);
        ApAuthor apAuthor =  articleFeign.findByUserId(apUserId);
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(UserConstans.AUTH_TYPE_SELF);
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(apUserId);
            apAuthor.setWmUserId(wmUser.getId());
            ResponseResult<ApAuthor> save = articleFeign.save(apAuthor);
            apAuthor = save.getData();
        }
        //ApAuthor apAuthor1 = articleFeign.findByUserId(apUserId);
       //给WmUser添加作者id；
        wmUser.setApAuthorId(apAuthor.getId());
        wemediaFeign.saveOrUpdate(wmUser);
    }

    /**
     * 状态监测
     * @param status
     * @return
     */
    private boolean statusCheck(Short status) {
        if (status == null
                || ( !status.equals(UserConstans.FAIL_AUTH)
                && !status.equals(UserConstans.PASS_AUTH))) {
            return true;
        }
        return false;
    }
}
